package com.easyexcel.demo.component;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.enums.WriteDirectionEnum;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.merge.LoopMergeStrategy;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easyexcel.demo.common.FileNameEnum;
import com.easyexcel.demo.converter.AdaptiveWidthStyleStrategy;
import com.easyexcel.demo.converter.CustomStyleStrategy;
import com.easyexcel.demo.service.UserService;
import com.easyexcel.demo.util.EasyExcelUtil;
import com.easyexcel.demo.vo.UserQuery;
import com.easyexcel.demo.vo.UserVO;
import com.google.common.collect.Lists;
import javafx.scene.control.Cell;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

import static cn.hutool.poi.excel.sax.ElementName.row;

/**
 * @author zhaoxh
 * @version : UserNoModelWrite.java, v 0.1 2023/12/22 zhaoxh Exp $
 * @desc 又来了横向扩展使用模版的导出需求
 */
@Component
public class UserHrizontalScalingService {

    @Resource
    private UserService userService;

    private static final String EXPORT_FILE_NAME_TEMPLATE = "【%s】用户信息导出";

    List<String> stringArrayList = Lists.newArrayList("数学", "语文", "英语", "物理", "化学", "生物", "地理", "历史", "政治", "音乐", "体育", "美术");


    @SneakyThrows
    public void exportExcel(HttpServletRequest request, HttpServletResponse response, UserQuery query) {
        // 初始化分页参数
        query.setCurrent(1);
        query.setSize(Integer.MAX_VALUE);

        // 设置响应头和文件名
        String fileName = String.format(EXPORT_FILE_NAME_TEMPLATE, DateUtil.now());
        EasyExcelUtil.setResponseHeaders(response, fileName);

        // 获取输出流并创建 ExcelWriter
        ServletOutputStream outputStream = response.getOutputStream();
        ExcelWriter excelWriter = EasyExcelUtil.excelWriterMerge(outputStream, UserVO.class, FileNameEnum.USER_TEACH_IMPORT, stringArrayList.size());

        WriteSheet writeSheet = EasyExcelFactory.writerSheet(FileNameEnum.USER_TEACH_IMPORT.getDesc()).build();

        // 填充模板固定数据（如日期）
        Map<String, Object> date = new HashMap<>();
        date.put("date", DateUtil.date().toString());
        excelWriter.fill(date, writeSheet);

        // 按组合向右扩展填充 {subject}、{teacher} 数据
        FillConfig fillConfig = FillConfig.builder()
                .forceNewRow(Boolean.TRUE)// 设置强制新行，否则数据会覆盖
                .direction(WriteDirectionEnum.HORIZONTAL).build();// 设置填充方向为水平方向
        List<Map<String, Object>> extensionData = getExtensionData(); // 获取扩展数据
        excelWriter.fill(extensionData, fillConfig, writeSheet);


        Page<UserVO> pageResult = userService.page(query);
        List<UserVO> records = pageResult.getRecords();
        if (CollectionUtil.isEmpty(records)) {
            return;
        }
        excelWriter.write(records, writeSheet);
        // 完成写入并关闭资源
        excelWriter.finish();
        outputStream.flush();
    }

    /**
     * 获取扩展数据
     *
     * @return
     */
    private List<Map<String, Object>> getExtensionData() {
        List<Map<String, Object>> list = new ArrayList<>();


        for (int i = 0; i < stringArrayList.size(); i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("course", stringArrayList.get(i));
            map.put("teacher", "老师");
            list.add(map);

            Map<String, Object> map2 = new HashMap<>();
            map2.put("course", "");
            map2.put("teacher", "课时");
            list.add(map2);
        }

        return list;
    }

    private List<Map<String, Object>> employeeData() {
        List<Map<String, Object>> list = new ArrayList<>();

        // 员工 1
        Map<String, Object> employee1 = new HashMap<>();
        employee1.put("姓名", "张三");
        employee1.put("性别", "男");
        employee1.put("年龄", 28);
        employee1.put("生日", "1995-05-20");
        employee1.put("薪水", 8500.00);
        employee1.put("创建时间", DateUtil.date().toString()); // 使用当前日期作为创建时间
        list.add(employee1);

        // 员工 2
        Map<String, Object> employee2 = new HashMap<>();
        employee2.put("姓名", "李四");
        employee2.put("性别", "女");
        employee2.put("年龄", 32);
        employee2.put("生日", "1991-12-15");
        employee2.put("薪水", 9200.00);
        employee2.put("创建时间", DateUtil.date().toString());
        list.add(employee2);

        // 员工 3
        Map<String, Object> employee3 = new HashMap<>();
        employee3.put("姓名", "王五");
        employee3.put("性别", "男");
        employee3.put("年龄", 25);
        employee3.put("生日", "1998-03-10");
        employee3.put("薪水", 7800.00);
        employee3.put("创建时间", DateUtil.date().toString());
        list.add(employee3);

        return list;

    }


}
